package com.hisense.hiioc.hismartplate.server.handler;

import com.alibaba.fastjson.JSONObject;
import com.hisense.hiioc.hismartplate.server.CmdDispatcher;
import com.hisense.hiioc.hismartplate.server.CoreManager;
import com.hisense.hiioc.hismartplate.server.DevClient;
import com.hisense.hiioc.hismartplate.service.CoreManagerService;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @Author: almo
 * @Date: 2018/12/5 下午4:05
 * @Version 1.0
 */
public class MessageHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private static final Logger logger = LoggerFactory.getLogger(MessageHandler.class);

    private CoreManager coreManager = CoreManager.getInstance();
    private CmdDispatcher cmdDispatcher = CmdDispatcher.getInstance();

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, TextWebSocketFrame textWebSocketFrame) {
        DevClient client = coreManager.getDevClientByChannel(channelHandlerContext.channel());
        if (client != null && client.isAuthorized()) {
            //ToDo 处理接收到的消息
            System.out.println("received message: " + textWebSocketFrame.text());
            cmdDispatcher.dispatch(textWebSocketFrame.text());
        }
    }

    @Override
    public void channelUnregistered(ChannelHandlerContext ctx) throws Exception {
        coreManager.removeChannel(ctx.channel());
        super.channelUnregistered(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        coreManager.removeChannel(ctx.channel());
        super.exceptionCaught(ctx, cause);
    }
}
